<script setup lang="ts">
import {ref} from 'vue';
import {Empty, message} from 'ant-design-vue';
import {Tree} from '#/components/shadcn-ui';
import {useDrawer, useForm} from '#/ui-kit';

import {findMenuListTree,} from '#/api/system/menu';
import {findRoleMenuIds, roleAuthority} from '#/api/system/role';

const dataList = ref([]);
const [Drawer, drawerApi] = useDrawer({
  destroyOnClose: true,
  onConfirm: async () => {
    await formApi.validateAndSubmitForm();
  },
  onBeforeClose: () => {
    drawerApi.setState({confirmLoading: false})
    drawerApi.setData({});
    formApi.resetForm();
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const [menuTreeList, roleMenuIds] = await Promise.all([
        findMenuListTree({}),
        findRoleMenuIds({roleId: drawerApi.getData()?.id})
      ]);
      dataList.value = menuTreeList;
      formApi.setValues({menuIdList: roleMenuIds}, false, false);
    }
  }
});

const [Form, formApi] = useForm({
  schema: [
    {
      component: 'Input',
      fieldName: 'menuIdList',
      modelPropName: 'modelValue',
      labelWidth: 0,
      formItemClass: 'pb-0'
    },
  ],
  showDefaultActions: false,
  handleSubmit: async (values) => {
    drawerApi.setState({confirmLoading: true});
    const params = {
      roleId: drawerApi.getData()?.id,
      menuIdList: values.menuIdList,
    };
    await roleAuthority(params).then(() => {
      message.success('角色授权成功');
      drawerApi.close();
    }).finally(() => {
      drawerApi.setState({confirmLoading: false});
    });
  }
});
</script>

<template>
  <Drawer>
    <Form v-if="dataList && dataList?.length > 0">
      <template #menuIdList="slotProps">
        <Tree
            v-bind="slotProps"
            :tree-data="dataList"
            value-field="id"
            label-field="title"
            icon-field="icon"
            multiple
            bordered
            :default-expanded-level="2"
        />
      </template>
    </Form>
    <Empty v-else/>
  </Drawer>
</template>